package amani.wechat.platform.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.print.attribute.standard.DateTimeAtCompleted;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mysql.fabric.xmlrpc.base.Array;

import amani.wechat.platform.controller.model.CommitOrdersReturnData;
import amani.wechat.platform.controller.model.NotifyReturnData;
import amani.wechat.platform.services.ICommonService;
import amani.wechat.platform.services.IShopService;
import amani.wechat.platform.services.impl.OrdersService;
import amani.wechat.platform.services.model.CompanyInfoEx;
import amani.wechat.platform.services.model.Product;
import amani.wechat.platform.services.model.ProductGroup;
import amani.wechat.platform.services.model.ShopCartItem;
import amani.wechat.platform.services.model.WxOrders;
import amani.wechat.platform.services.model.WxOrdersDetail;
import amani.wechat.platform.utils.WxUtils;
import amani.wechat.platform.webserviceClient.Companyinfo;

/**
 * 家具前台首页
 * 
 * @author VV
 *
 */
@Controller
@RequestMapping("/Shop")
public class ShopController {

	@Resource(name = "ShopService")
	IShopService shopService;

	@Resource(name = "CommonService")
	ICommonService commonService;
	
	@RequestMapping("/Success")
	public String success( Model model) { 
		return "shop/sucess";
	}

	/**
	 * 分组的ID
	 * 
	 * @param groupId
	 * @return
	 */
	@RequestMapping("/Index")
	public String index(String groupId, Model model) {

		List<ProductGroup> groups = shopService.getProductGroups();
		model.addAttribute("Groups", groups);

		if (groupId == null || groupId.equals("")) {
			groupId = Integer.toString(groups.get(0).getId());
		}
		List<Product> products = shopService.getProductsByGroupId(groupId);
		model.addAttribute("products", products);
		model.addAttribute("selectGroup", groupId);

		return "shop/index";
	}

	/**
	 * 
	 * @param itemId
	 *            商品的ID
	 * @return
	 */
	@RequestMapping("/ItemDetails")
	public String itemDetails(String itemId, Model model) {
		Product product = shopService.getProductById(itemId);
		product.setProductDescriptions(shopService.getProductDescriptions(product.getId().toString()));
		model.addAttribute("product", product);
		return "shop/itemDetails";
	}

	/**
	 * 购物车
	 * 
	 * @param itemId
	 * @return
	 */
	@RequestMapping("/ShoppingCart")
	public String ShoppingCart(String addProductId, String deleteCartItemId,
			HttpServletRequest request, Model model) {
		if (request.getSession().getAttribute("ShopCart") == null) {
			request.getSession().setAttribute("ShopCart",
					new ArrayList<ShopCartItem>());
		}
		List<ShopCartItem> items = (List<ShopCartItem>) request.getSession()
				.getAttribute("ShopCart");

		if (!(addProductId == null || addProductId.equals(""))) {
			Product product = shopService.getProductById(addProductId);
			boolean isExit = false;
			ShopCartItem item = null;
			for (int i = 0; i < items.size(); i++) {
				if (items.get(i).getProductId() == product.getId()) {
					isExit = true;
					item = items.get(i);
					break;
				}
			}
			item = isExit ? item : new ShopCartItem();
			item.setName(product.getName());
			item.setPrice(product.getPrice());
			item.setProductId(product.getId());
			int currentNum = isExit ? item.getNum() : 0;
			item.setNum(currentNum + 1);
			if (!isExit) {
				List<Integer> ids = new ArrayList<Integer>();
				for (int i = 0; i < items.size(); i++) {
					ids.add(items.get(i).getId());
				}
				int id = 0;
				if (ids.size() > 0) {
					Arrays.sort(ids.toArray());
					id = ids.get(ids.size() - 1);
				}
				item.setId(id);
				items.add(item);
			}
		}

		request.getSession().setAttribute("ShopCart", items);
		model.addAttribute("ShopCartItems", items);
		return "shop/shoppingcart";
	}

	@RequestMapping("/DeleteShoppingCartItem")
	@ResponseBody
	public NotifyReturnData DeleteShoppingCartItem(String deleteCartItemId,
			HttpServletRequest request, HttpServletResponse reponse) {
		List<ShopCartItem> items = (List<ShopCartItem>) request.getSession()
				.getAttribute("ShopCart");
		if (!(deleteCartItemId == null || deleteCartItemId.equals(""))) {
			boolean isExit = false;
			int removeIndex = -1;
			for (int i = 0; i < items.size(); i++) {
				if (items.get(i).getId() == Integer.parseInt(deleteCartItemId)) {
					isExit = true;
					removeIndex = i;
					break;
				}
			}
			if (isExit) {
				items.remove(removeIndex);
			}
		}
		request.getSession().setAttribute("ShopCart", items);
		NotifyReturnData resultData = new NotifyReturnData();
		resultData.setReturn_code("1");
		resultData.setReturn_msg("");
		return resultData;
	}

	@RequestMapping("/ShoppingCount")
	public String ShoppingCount(String ids, HttpServletRequest request,
			Model model) {

		List<Companyinfo> temp = commonService.loadAllCompanyinfo();

		List<CompanyInfoEx> Companyinfos = new ArrayList<CompanyInfoEx>();

		for (int i = 0; i < temp.size(); i++) {
			Companyinfos.add(new CompanyInfoEx(temp.get(i)));
		}
		model.addAttribute("Companies", Companyinfos);

		model.addAttribute("ids", ids);

		String[] arrayId = ids.split(",");
		List<ShopCartItem> items = (List<ShopCartItem>) request.getSession()
				.getAttribute("ShopCart");
		if (items != null && temp != null) {
			double totalAmount = 0;
			for (int j = 0; j < arrayId.length; j++) {
				int index = -1;
				for (int i = 0; i < temp.size(); i++) {
					ShopCartItem item = items.get(i);
					if (item.getId() == Integer.parseInt(arrayId[j])) {
						index = i;
						break;
					}
				}
				if (index != -1) {
					ShopCartItem item = items.get(index);
					totalAmount += (item.getPrice() * item.getNum());
				}
			}
			model.addAttribute("totalAmount", totalAmount);
		}
		SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String orderno = "JJ-" + sFormat.format(new Date())
				+ _random.nextInt(1000); 
		model.addAttribute("orderno", orderno);
		return "shop/shoppingcount";
	}

	private static Random _random = new Random();

	/**
	 * 下单操作
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/Orders")
	@ResponseBody
	public CommitOrdersReturnData Orders(String ids, String isExpress,String totalAmount,
			String address, String username, String phone, String compno,String orderno,
			HttpServletRequest request) throws Exception {
		Map<String, Object> map=  commonService.loadWxOrderByOrderNo(orderno); 
		String clientIP = (String) request.getSession()
				.getAttribute("clientIp"); 
		String opendid = (String) request.getSession().getAttribute("openid");
		Double price=Double.parseDouble(totalAmount);
		if(map!=null){
			CommitOrdersReturnData returnData=new CommitOrdersReturnData();
			JSONObject payJsonData = WxUtils.GeneratePayJosn(orderno, opendid,
					orderno, price, clientIP);//获取支付json数据
			returnData.setPayJsonData(payJsonData); 
			returnData.setIsSuccessed(false);
			return returnData;  
		}
		
		
		String currentmemberno = (String) request.getSession().getAttribute(
				"currentmemberno");
		WxOrders orders = new WxOrders();
		if(isExpress.equals("1")){
			orders.setAddress(getString(address));
			orders.setUsername(getString(username));
			orders.setPhone(getString(phone));
		}
		orders.setUseropenid(opendid);
		if(isExpress.equals("0")){
			List<Companyinfo> temp = commonService.loadAllCompanyinfo();
			CompanyInfoEx companyInfoEx = null;
			for (int i = 0; i < temp.size(); i++) {
				if (temp.get(i).getCompno().getValue().equals(compno)) {
					companyInfoEx = new CompanyInfoEx(temp.get(i));
					break;
				}
			}
			if (companyInfoEx != null) {
				orders.setCompno(companyInfoEx.getCompno());
				orders.setCompname(companyInfoEx.getCompname());
				orders.setCompanyaddress(companyInfoEx.getCompaddress());
			}
		}
		orders.setWxOrdersDetail(new ArrayList<WxOrdersDetail>());
		
		List<ShopCartItem> items = (List<ShopCartItem>) request.getSession()
				.getAttribute("ShopCart");
		/*double totalAmount = 0;
		String[] arrayId = ids.split(",");
		for (int j = 0; j < arrayId.length; j++) {
			int index = -1;
			for (int i = 0; i < items.size(); i++) {
				ShopCartItem item = items.get(i);
				if (item.getId() == Integer.parseInt(arrayId[j])) {
					index = i;
					break;
				}
			}
			if (index != -1) {
				ShopCartItem item = items.get(index);
				WxOrdersDetail detail = new WxOrdersDetail();
				detail.setNumber(item.getNum());
				detail.setAmnProductId(item.getProductId());
				orders.getWxOrdersDetail().add(detail);
				totalAmount += (item.getPrice() * item.getNum());
			}
		}*/
		items.clear();

		orders.setTotalAmount(price);
		orders.setMemberno(currentmemberno);
		orders.setOrderno(orderno);

		shopService.saveOrder(orders);

		CommitOrdersReturnData commitOrdersReturnData = new CommitOrdersReturnData();
		commitOrdersReturnData.setIsSuccessed(true);

	
		JSONObject payJsonData = WxUtils.GeneratePayJosn(orderno, opendid,
				orderno, price, clientIP);//获取支付json数据
		commitOrdersReturnData.setPayJsonData(payJsonData); 
		return commitOrdersReturnData;
	}

	private String getString(String value) {
		return (value == null || value.equals("")) ? "" : value;
	}

}
